using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;

namespace Rally_Dekstop
{
    public partial class GUITasksViewer : Form
    {
       // private Hashtable defectTable = new Hashtable();
        private IRallyService service = null;
        private Hashtable tempCache = new Hashtable();
        private bool cacheSet = false;
        private string tempFilePathDesc = string.Empty;
        private string tempFilePathNotes = string.Empty;
        private string tempFileBlank = string.Empty;
        private enum FileTypes { Zip, Doc, Ppt, Xml, Xbrl, Xsd, Xls, Xlt, Txt, SevenZ, Rar, Html, JPEG, GIF, BMP };
        
        private TaskDataCache taskCacheData = new TaskDataCache();
        private string TaskCacheKey = RallyDesk.CacheKey + RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef + "TaskCache";

        private Hashtable fromThread;
        private bool threadCacheFlag = false;

        private object parent = null;

        public GUITasksViewer(object listener)
        {
            InitializeComponent();
            parent = listener;
            this.MdiParent = Rally_Dekstop.Program.RallyMain;
            this.WindowState = FormWindowState.Normal;
            FillData();
            RefreshCache();
            lstBoxAttachments.Text = string.Empty;
            htmlEditorDesc.IsEditMode = false;
            htmlEditorNotes.IsEditMode = false;
            this.Tag = VisibleFormType.TASK_VIEWER;
            
        }

        private void GUITasksViewer_Load(object sender, EventArgs e)
        {



            
            
        }
        private string CreateQueryString()
        {
            string queryString = string.Empty;
            queryString = "(Owner = \"" + RallyDesk.Username + "\")";
            return queryString;
        }
        public void ClearTaskData()
        {
            gBoxTasks.Text = "My Tasks :";
            tabPage_Task.Text = "Task";
            txtId.Text = string.Empty;
            txtName.Text = string.Empty;
            htmlEditorDesc.HTMLText = string.Empty;
            htmlEditorNotes.HTMLText = string.Empty;

            txtActuals.Text = string.Empty;
            txtCard.Text = string.Empty;
            txtEstimate.Text = string.Empty;
            txtOwner.Text = string.Empty;
            txtState.Text = string.Empty;
            txtToDo.Text = string.Empty;
            chk_Blocked.CheckState = CheckState.Unchecked;
        }

        private void GUITasksViewer_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (RallyDesk.Cache.Contains(TaskCacheKey))
                RallyDesk.Cache.Edit(TaskCacheKey, taskCacheData);
            else
                RallyDesk.Cache.Add(TaskCacheKey, taskCacheData);
           
        }
        private void RefreshCache()
        {
            this.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            SetTaskCache();
            this.Cursor = Cursors.Default;
            this.Enabled = true;

            Rally_Dekstop.Program.RallyMain.Cursor = Cursors.Default;
            this.ClearForm();
        }
        public void SetTaskCache()
        {
            if (!cacheSet)
            {
                taskCacheData.TaskCache.Clear();
               if (RallyDesk.Cache.Contains(TaskCacheKey))
                {
                    taskCacheData.TaskCache = ((TaskDataCache)RallyDesk.Cache.Get(TaskCacheKey)).TaskCache;
                    taskCacheData.CacheTimeStamp = ((TaskDataCache)RallyDesk.Cache.Get(TaskCacheKey)).CacheTimeStamp;
                }
                else
                {

                   taskCacheData.TaskCache = GetTaskData(cacheSet);

                    taskCacheData.CacheTimeStamp = Utilities.CovertToRallyTimeStamp(System.DateTime.UtcNow);
                    
                }


                cacheSet = true;

            }
            else
            {
                tempCache = GetTaskData(cacheSet);
                foreach (Task task in tempCache)
                {
                    if (taskCacheData.TaskCache.ContainsKey(task.ID))
                    {
                        if (task.Owner == RallyDesk.Username)
                        {
                            taskCacheData.TaskCache.Remove(task.ID);
                            taskCacheData.TaskCache.Add(task.ID, task);
                        }
                        else
                        {
                            taskCacheData.TaskCache.Remove(task.ID);
                            taskCacheData.TaskCache.Remove(task.ID);
                        }

                    }
                    else
                        taskCacheData.TaskCache.Add(task.ID, task);
                }

            }

        }

        private Hashtable GetTaskData(bool cacheisSet)
        {
            threadCacheFlag = cacheisSet;
            Thread toRunService = new Thread(new ThreadStart(ExecuteServiceRequest));
            toRunService.Start();
            ((RallyDesk)parent).toolStripStatusLabel.Text = "Getting Tasks...";
            ((RallyDesk)parent).ProgressBarMain.Style = ProgressBarStyle.Marquee;
            ((RallyDesk)parent).ProgressBarMain.Visible = true;
            while (toRunService.IsAlive)
            {

                Application.DoEvents();
            }

            toRunService.Abort();
            ((RallyDesk)parent).ProgressBarMain.Visible = false;
            ((RallyDesk)parent).toolStripStatusLabel.Text = "Ready";
            return fromThread;

        }
        private void ExecuteServiceRequest()
        {
            if (service == null)
            {
                if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UseCase")
                    service = new RallyAPIUseCase(RallyDesk.url);
                else
                    service = new RallyAPIUserStory(RallyDesk.url);
            }



            if (!threadCacheFlag)
            {
                string queryString = CreateQueryString();
                if (queryString.Length > 0)
                {


                    fromThread = service.GetTasks(queryString);
                    //queryResult = service.UpdatedDefects("2007-07-02T11:2:19.000Z");


                }
            }
            else
            {
                fromThread = service.UpdatedTasks(taskCacheData.CacheTimeStamp);


            }


        }
        public void ClearCache()
        {
            taskCacheData.TaskCache.Clear();
            taskCacheData.CacheTimeStamp = string.Empty;
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            RefreshCache();
        }

        private void btnGetResults_Click(object sender, EventArgs e)
        {
            GetResults();
            
        }
        private void GetResults()
        {
            if (taskCacheData.TaskCache.Count > 0)
            {
                ArrayList taskIDs = GetFilteredData();
                lstViewTasks.Items.Clear();
                if (taskIDs.Count == 0)
                    gBoxTasks.Text = "My Tasks : ";

                foreach (string taskID in taskIDs)
                {
                    string[] data = { taskID, ((Task)taskCacheData.TaskCache[taskID]).Name };
                    ListViewItem item = new System.Windows.Forms.ListViewItem(data);
                    lstViewTasks.Items.Add(item);

                    gBoxTasks.Text = "My Tasks : " + Convert.ToString(taskIDs.Count);
                }
                this.ClearTaskData();
            } 

        }
        
        private ArrayList GetFilteredData()
        {
            ArrayList filteredData = new ArrayList();

            if (cmbState.SelectedIndex != -1 || cmbBlocked.SelectedIndex != -1)
            {
                bool isStateSet = (cmbState.SelectedItem.ToString().Equals("All")) ? false : true;
                bool isBlockedSet = (cmbBlocked.SelectedItem.ToString().Equals("All")) ? false : true;
                

                if (!isStateSet && !isBlockedSet)
                {
                    foreach (Task task in taskCacheData.TaskCache.Values)
                    {
                        filteredData.Add(task.ID);
                    }
                }
                else
                {
                    foreach (Task task in taskCacheData.TaskCache.Values)
                    {
                        bool result = false;

                        if (isStateSet)
                        {
                            result = (task.State == cmbState.SelectedItem.ToString());
                        }
                        

                        if (result)
                        {
                            if (isBlockedSet)
                            {
                                result = (task.Blocked.ToString() == cmbBlocked.SelectedItem.ToString());
                            }
                        }

                        if (result)
                            filteredData.Add(task.ID);


                    }
                }

            }

            return filteredData;
        }

        private void FillData()
        {
            cmbState.Items.Add("All");
            foreach (string state in RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.Task.States)
            {
                if (state.Trim().Length > 0)
                    cmbState.Items.Add(state);
            }
            this.cmbState.SelectedIndex = 0;
             this.btnGetResults.PerformClick();
        }
        public void ClearForm()
        {
            this.lstViewTasks.Items.Clear();
            this.cmbBlocked.SelectedIndex = 0;
            this.cmbState.SelectedIndex = 0;
            this.GetResults();
            this.ClearTaskData();

        }
        private void PopulateTaskData(Task task)
        {
            tabPage_Task.Text = task.ID;
            
            txtId.Text = task.ID;
            txtName.Text = task.Name;
            txtOwner.Text = task.Owner;
            htmlEditorDesc.HTMLText = "<html>" + task.Description + "</html>";
            htmlEditorDesc.IsEditMode = false;
            htmlEditorNotes.HTMLText = "<html>" + task.Notes + "</html>";
            htmlEditorNotes.IsEditMode = false;

            txtActuals.Text = task.Actuals;
            txtCard.Text = task.StoryCard;
            txtEstimate.Text = task.Estimate;
            txtState.Text = task.State;
            txtToDo.Text = task.ToDO;
            chk_Blocked.Checked = task.Blocked;
            
            lstBoxAttachments.Items.Clear();
            if (task.AttachmentList.Count > 0)
            {
                label_attachments.Text = Convert.ToString(task.AttachmentList.Count) + " Attachments :";
                foreach (Attachment attachment in task.AttachmentList)
                {
                    string[] data = { attachment.AttachmentName };
                    ListViewItem item = new System.Windows.Forms.ListViewItem(data);
                    lstBoxAttachments.Items.Add(item);
                    string[] str = attachment.AttachmentName.Split('.');
                    item.ImageIndex = GetImageIndex(str[str.Length - 1]);

                }
            }
            else
                label_attachments.Text = "0 Attachments :";

        }
        private int GetImageIndex(string fileType)
        {
            int imageIndex = 0;

            switch (fileType)
            {
                case "zip":
                    {
                        imageIndex = 4;
                        break;
                    }
                case "doc":
                    {
                        imageIndex = 1;
                        break;
                    }
                case "html":
                    {
                        imageIndex = 12;
                        break;
                    }
                case "xls":
                    {
                        imageIndex = 11;
                        break;
                    }
                case "ppt":
                    {
                        imageIndex = 10;
                        break;
                    }
                case "xsd":
                    {
                        imageIndex = 9;
                        break;
                    }
                case "xml":
                    {
                        imageIndex = 5;
                        break;
                    }
                case "7z":
                    {
                        imageIndex = 0;
                        break;
                    }
                case "txt":
                    {
                        imageIndex = 8;
                        break;
                    }
                case "rar":
                    {
                        imageIndex = 6;
                        break;
                    }
                case "jpg":
                    {
                        imageIndex = 3;
                        break;
                    }
                case "jpeg":
                    {
                        imageIndex = 3;
                        break;
                    }
                case "xbrl":
                    {
                        imageIndex = 7;
                        break;
                    }
                default:
                    {
                        imageIndex = 0;
                        break;
                    }
            }

            return imageIndex;
        }
        private void lstViewTasks_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void lstViewTasks_MouseClick(object sender, MouseEventArgs e)
        {

        }

        private void lstViewTasks_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void lstViewTasks_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstViewTasks.SelectedItems.Count > 0)
            {
                if (taskCacheData.TaskCache.Contains(lstViewTasks.SelectedItems[0].Text))
                {
                    DeleteTempFiles();
                    PopulateTaskData((Task)taskCacheData.TaskCache[lstViewTasks.SelectedItems[0].Text]);
                }
            }
        }
        private void DeleteTempFiles()
        {

            if (System.IO.File.Exists(tempFilePathDesc + "_Temp.html"))
                System.IO.File.Delete(tempFilePathDesc + "_Temp.html");

            if (System.IO.File.Exists(tempFilePathNotes + "_Temp.html"))
                System.IO.File.Delete(tempFilePathNotes + "_Temp.html");
        }

    
    }
}